package com.kongchengji.zhanguafou.controller;
import com.kongchengji.zhanguafou.constant.WxInfo;
import com.kongchengji.zhanguafou.dao.QuartzDAO;
import com.kongchengji.zhanguafou.domain.QuartzDO;
import com.kongchengji.zhanguafou.domain.Result;
import com.kongchengji.zhanguafou.domain.ServerDO;
import com.kongchengji.zhanguafou.service.ServerService;
import com.kongchengji.zhanguafou.utils.InfoByCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletResponse;


@Controller
public class ServerController {
    @Autowired
    ServerService serverService;
    @Autowired
    QuartzDAO quartzDAO;

    @RequestMapping("/serverConfig")
    public String forWardServerConfig(@RequestParam String code,Model model){
        WxInfo.openId = InfoByCodeUtil.getOpenId(code);
        model.addAttribute("isSave",true);
        return "server_config";
    }

    @RequestMapping("/saveConfig")
    @ResponseBody
    public Result saveServerConfig(@Validated ServerDO serverDO, BindingResult bindingResult){
        serverDO.setOpenId(WxInfo.openId);
        if(bindingResult.hasErrors()){
            for(ObjectError error:bindingResult.getAllErrors()){
                return Result.error(error.getDefaultMessage());
            }
        }
       return serverService.saveConfig(serverDO);
    }

    /**
     * 打开服务监控编辑页面
     * @param groupName 可能参数就是:Ping + ip
     * @return
     */
    @RequestMapping("/openServerEditPage")
    public String openEditPage(String groupName,Model model,HttpServletResponse response) {
        //组成计划任务的唯一标识
        String jobName = groupName + WxInfo.openId;
        Example example = new Example(QuartzDO.class);
        example.createCriteria().andEqualTo("jobName",jobName);
        QuartzDO quartzDO = quartzDAO.selectOneByExample(example);
        //因为这个任务执行的时间间隔是分钟，cron表达式形式类似于 0 0/min * * * ?
        String cron = quartzDO.getCronExpression();
        String min = cron.substring("0 0/".length(),cron.indexOf(" ","0 0/".length()));
        model.addAttribute("quartzDO",quartzDO);
        model.addAttribute("min",min);
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        model.addAttribute("isQuartzEdit",true);
        return "server_config";
    }




}
